package com.example.chatzsyproject.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.chatzsyproject.R;
import com.example.chatzsyproject.app.MyApplication;
import com.example.chatzsyproject.base.BaseActivity;
import com.example.chatzsyproject.utils.HttpConfig;
import com.example.chatzsyproject.utils.HttpResult;
import com.example.chatzsyproject.utils.OkHttpClientUtils;
import com.example.chatzsyproject.utils.Utils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.lvfq.library.utils.LvToastUtil;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_paw)
    EditText et_paw;
    @BindView(R.id.tv_findpassword)
    TextView tv_findpassword;
    //    @BindView(R.id.tv_yzm)
//    Chronometer tvYzm;
    @BindView(R.id.bt_login)
    Button bt_login;
    @BindView(R.id.bt_regist)
    Button bt_regist;

//    private Chronometer sendCheckCode = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (MyApplication.MySharedPreferences.readIsLogin()) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        } else {
            setContentView(R.layout.activity_login);
            ButterKnife.bind(this);
            init();
        }
    }

    public void init() {
//        sendCheckCode = (Chronometer) findViewById(R.id.tv_yzm);
//        sendCheckCode.setText("获取验证码");
//        sendCheckCode.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                String phone = etUsername.getText().toString();
//                if (TextUtils.isEmpty(phone)) {
//                    Toast.makeText(LoginActivity.this, "请输入11位手机号码", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                if (!Utils.isMobile(phone)) {
//                    Toast.makeText(LoginActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//
//                // 先隐藏输入法
//                InputMethodManager imm = (InputMethodManager) LoginActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
//                yanZhengMa();
//            }
//        });
//        sendCheckCode.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
//            @Override
//            public void onChronometerTick(Chronometer chronometer) {
//                long time = (Long) chronometer.getTag() - SystemClock.elapsedRealtime() / 1000;
//                if (time > 0) {
//                    chronometer.setText("（" + time + "）重新获取");
//                } else {
//                    chronometer.setText("重新获取");
//                    chronometer.stop();
//                    chronometer.setEnabled(true);
//                }
//            }
//        });
//        sendCheckCode.setText("获取验证码");
        bt_login.setOnClickListener(this);
        bt_regist.setOnClickListener(this);
        tv_findpassword.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_findpassword:
                startActivity(new Intent(LoginActivity.this, FindPasswordActivity.class));
                break;
            case R.id.bt_login:
                if (TextUtils.isEmpty(etUsername.getText().toString())) {
                    Toast.makeText(LoginActivity.this, "用户名不可以为空", Toast.LENGTH_LONG).show();
                } else if (TextUtils.isEmpty(et_paw.getText().toString())) {
                    LvToastUtil.showToast(this, "密码不可以为空");
                } else {
                    login();
                }
                break;
            case R.id.bt_regist:
                regist();
                break;
        }
    }

    /**
     * 注册
     */
    public void regist() {
        startActivity(new Intent(LoginActivity.this, RegistActivity.class));
    }

    /**
     * 登录
     */
    public void login() {
        Map<String,String> map = new TreeMap<>();
        map.put("account",etUsername.getText().toString());
        map.put("password",et_paw.getText().toString());
        OkHttpClientUtils.doPost(HttpConfig.login, map, new HttpResult() {
            @Override
            public void succ(String s) {
                EMClient.getInstance().login(etUsername.getText().toString(), et_paw.getText().toString(), new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();

                        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
                        Set<String> conversations_key = conversations.keySet();

                        MyApplication.MySharedPreferences.saveIsLogin(true);
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                        Log.e("wsy", "登录聊天服务器失败！");
                    }

                    @Override
                    public void onError(int code, String message) {
                        Log.e("wsy", "登录聊天服务器失败！" + message + "   -----   " + code);
                    }
                });
            }

            @Override
            public void error() {

            }

            @Override
            public void start() {

            }
        });
    }

    /**
     * 获取验证码
     */
    public void yanZhengMa() {
        yzmStart();
    }

    public void yzmStart() {
//        sendCheckCode.setTag(SystemClock.elapsedRealtime() / 1000 + 60);
//        sendCheckCode.setText("（60）重新获取");
//        sendCheckCode.start();
//        sendCheckCode.setEnabled(false);

        getWindow()
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}
